package web_programing.review.Tcp;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @author haomin
 * @date 2022/09/27 18:33
 **/
// UDP: 无连接       面向数据报文-写信（一信一送）
// TCP: 有连接       面向字节流  -写信（一堆信一送）-打电话(连接好才行)
public class Server {
    private static final HashMap<String, String> map = new HashMap<>();
    static {
        map.put("apple", "苹果");
        map.put("banana", "香蕉");
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true){
            // 1. 接通连接（电话） —— accept
            Socket socket = serverSocket.accept(); // 阻塞
            InetAddress inetAddress = socket.getInetAddress(); // 得到客户端地址
            int port = socket.getPort();                       // 得到客户端端口

            InputStream is = socket.getInputStream();  // is: 用于读数据
            OutputStream os = socket.getOutputStream();// os: 用于写数据

            // 2. 读取请求
            Scanner scanner = new Scanner(is, "utf-8");
            String header = scanner.nextLine();
            String englishWord = scanner.nextLine();

            // 3. 处理业务
            String chineseWord = map.getOrDefault(englishWord, "不认识");

            // 4. 发送响应
            // 好的\r\n苹果\r\n
            // OutputStream -> OutputStreamWriter -> PrintWriter
            OutputStreamWriter writer = new OutputStreamWriter(os, "utf-8");
            PrintWriter printWriter = new PrintWriter(writer);

            printWriter.printf("好的\r\n%s\r\n", chineseWord);
            printWriter.flush();

            socket.close();
            Log.println("服务器响应成功");
        }
    }
}